package com.zoe.onelink.util;

import cn.hutool.core.io.IoUtil;
import cn.hutool.http.ContentType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.ContentCachingRequestWrapper;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * <p>标题: Spring工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-10-21
 */
public class SpringUtil extends cn.hutool.extra.spring.SpringUtil {

    public static final String STREAM_CLOSED = "STREAM_CLOSED";

    /**
     * 获取请求文本
     */
    public static String getRequestBody(HttpServletRequest servletRequest) throws IOException {
        String reqBody;
        if (servletRequest instanceof ContentCachingRequestWrapper) {
            ContentCachingRequestWrapper cachedRequest = (ContentCachingRequestWrapper) servletRequest;
            byte[] requestBodyBytes = cachedRequest.getContentAsByteArray();
            if (requestBodyBytes.length > 0) {
                reqBody = new String(requestBodyBytes, 0, requestBodyBytes.length, cachedRequest.getCharacterEncoding());
            } else {
                reqBody = IoUtil.read(cachedRequest.getReader());
            }
        } else if (servletRequest.getAttribute(STREAM_CLOSED) == null) {
            reqBody = IoUtil.read(servletRequest.getReader());
            servletRequest.setAttribute(STREAM_CLOSED, 1);
        } else {
            reqBody = null;
        }

        if (StrUtil.isBlank(reqBody)) {
            return null;
        }
        return reqBody;
    }

    /**
     * 获取当前请求对象
     */
    public static HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return null;
        }
        return ((ServletRequestAttributes) requestAttributes).getRequest();
    }

    /**
     * 获取请求头
     *
     * @param headerName 请求头名称
     */
    public static String getRequestHeader(String headerName) {
        HttpServletRequest request = getRequest();
        return request == null ? "" : request.getHeader(headerName);
    }

    public static boolean isApplicationJson(String contentType) {
        if (contentType == null) {
            return false;
        }
        return contentType.contains(ContentType.JSON.getValue());
    }

}
